<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <div class="content">
          <NSpace>
            <NForm
              ref="formRef"
              :model="formValue"
              :rules="rules"
              label-placement="left"
              :label-width="115"
              label-align="right"
              require-mark-placement="left"
            >
              <NFormItem
                label="公告标题:"
                path="noticeTitle"
              >
                <NInput
                  v-model:value="formValue.noticeTitle"
                  placeholder="输入公告标题"
                  style="width: 500px"
                  @input="inputNoticeTitle"
                />
              </NFormItem>
              <NFormItem
                label="公告时间:"
                path="datetime"
              >
                <NDatePicker
                  input-readonly
                  v-model:formatted-value="datetime"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  @update:formatted-value="changeDate"
                  style="width: 500px"
                />
              </NFormItem>
              <NFormItem
                label="征集说明:"
                path="description"
              >
                <div style="border: 1px solid #dcdfe6; width: 600px; border-radius: 4px">
                  <toolbar
                    style="border-bottom: 1px solid #dcdfe6; width: 100%; border-radius: 4px"
                    :editor="editorRef"
                    :default-config="toolbarConfig"
                    mode="default"
                  />
                  <editor
                    v-model="formValue.description"
                    style="height: 200px; overflow-y: hidden"
                    :default-config="editorConfig"
                    mode="default"
                    @onCreated="onCreated"
                  />
                </div>
              </NFormItem>
              <!-- <NFormItem
                label="征集提示:"
                path="prompt"
              >
                <NInput
                  v-model:value="formValue.prompt"
                  placeholder="请输入征集提示"
                  type="textarea"
                />
              </NFormItem> -->
            </NForm>
          </NSpace>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="confirm"
        :disabled="loading"
        :loading="loading"
      >
        保存
      </NButton>
    </NSpace>
  </FixedAction>
</template>

<script setup lang="ts">
import { ref, nextTick, shallowRef, reactive } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NDatePicker,
  useMessage
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import { getToken } from '@/utils/auth'
import type { HttpResponse } from '@/utils/http'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

//富文本
const editorRef = shallowRef()
// 菜单配置
const toolbarConfig = ref({
  toolbarKeys: [
    'bold', // 加粗
    'italic', // 斜体
    'through', // 删除线
    'underline', // 下划线
    'color', // 文字颜色
    'insertLink', // 插入链接
    'fontSize', // 字体大小
    'uploadImage', // 上传图片
    // 'delIndent', // 缩进
    // 'indent', // 增进
    // 'deleteImage',//删除图片
    // 'divider', // 分割线
    // 'insertTable', // 插入表格
    'justifyCenter', // 居中对齐
    'justifyJustify', // 两端对齐
    'justifyLeft', // 左对齐
    'justifyRight', // 右对齐
    'undo', // 撤销
    // 'redo', // 重做
    'clearStyle' // 清除格式
  ]
})
const token = getToken()
// 编辑器配置
const editorConfig = ref({
  placeholder: '请输入内容...',
  readOnly: false, // 只读
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      server: `${import.meta.env.VITE_API_BASE_URL}/common/annexFile/uploadRichFile`, // 配置图片上传地址
      headers: {
        Token: token || ' '
      },
      maxFileSize: 10 * 1024 * 1024, // 10M  图片大小限制
      fieldName: 'file', // 上传名字
      allowedFileTypes: ['image/*'], // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      // 自定义上传参数，传递图片时需要带一些参数过去写在这。参数会被添加到 formData 中，一起上传到服务端。
      // meta: {
      //   image_class_id: "2",
      //   file_type: "1",
      // },
      // 自定义设置请求头，比如添加token之类的
      // headers: {
      //     Accept: 'text/x-json',
      //     otherKey: 'xxx'
      // },
      onBeforeUpload(file: File) {
        // TS 语法
        console.log(file)
        const values = Object.values(file)
        console.log(values[0].type)
        if (
          values[0].type !== 'image/jpeg' &&
          values[0].type !== 'image/png' &&
          values[0].type !== 'image/gif' &&
          values[0].type !== 'image/jpg' &&
          values[0].type !== 'image/tiff' &&
          values[0].type !== 'image/jfif' &&
          values[0].type !== 'image/bmp' &&
          values[0].type !== 'image/svg' &&
          values[0].type !== 'image/svgz' &&
          values[0].type !== 'image/webp' &&
          values[0].type !== 'image/ico' &&
          values[0].type !== 'image/xbm' &&
          values[0].type !== 'image/dib' &&
          values[0].type !== 'image/pjp' &&
          values[0].type !== 'image/apng' &&
          values[0].type !== 'image/tif' &&
          values[0].type !== 'image/pjpeg' &&
          values[0].type !== 'image/avif' &&
          values[0].type !== 'image/svg+xml' &&
          values[0].type !== 'image/x-icon'
        ) {
          message.error('只能上传图片文件，请重新上传')
          return false
        } else {
          return file
        }
      },

      // 上传进度的回调函数，可以用来显示进度条
      onProgress(progress: any) {
        // progress 是 0-100 的数字
        console.log('progress', progress)
      },
      // 单个文件上传成功之后
      onSuccess(file: any, res: any) {
        console.log(`${file.name} 上传成功`, res)
      },

      // 单个文件上传失败
      onFailed(file: any, res: any) {
        console.log(`${file.name} 上传失败`, res)
      },

      // 上传错误，或者触发 timeout 超时
      onError(file: any, err: any, res: any) {
        console.log(`${file.name} 上传出错`, err, res)
      },

      // 插入图片到富文本编辑器回显
      customInsert(res: any, insertFn: any) {
        console.log(res)
        // res 即服务端的返回结果
        // getPhotoUrl(res.data[0]).then((res) => {
        const url = res.data.url
        const alt = res.data.alt
        const href = res.data.href
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(url, alt, href)
        // })
      }
    },
    fontFamily: {
      fontFamilyList: [
        // 元素支持两种形式
        //   1. 字符串；
        //   2. { name: 'xxx', value: 'xxx' }

        { name: '仿宋', value: '仿宋' }
      ]
    }
  }
})
const onCreated = (editor: any) => {
  editorRef.value = editor
  nextTick(() => {
    editorRef.value = editor // 一定要用 Object.seal() ，否则会报错
  })
  // editor.config.uploadHeaders = {'authentication':'111'};
}
const tags = useTagStore().tags
const message = useMessage()
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const formValue = reactive({
  noticeTitle: '',
  description: '',
  prompt: '',
  startDate: '',
  endDate: ''
})
const datetime = ref(null)
const rules = {
  noticeTitle: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('输入公告标题')
      if (value.length > 100) return new Error('公告标题字数不得超过100')
      return true
    }
  },
  datetime: {
    required: true,
    trigger: ['change', 'blur'],
    validator: () => {
      if (!datetime.value) return new Error('请选择公告时间')
      return true
    }
  },
  description: {
    required: true,
    trigger: ['change', 'input', 'blur'],
    validator: () => {
      if (formValue.description === '<p><br></p>') return new Error('请输入征集说明')
      return true
    }
  },
  prompt: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length > 500) return new Error('征集提示字数不得超过500')
      return true
    }
  }
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
const changeDate = (v: any) => {
  datetime.value = v
  formValue.startDate = v ? v[0] : null
  formValue.endDate = v ? v[1] : null
}
const inputNoticeTitle = (v: any) => {
  formValue.noticeTitle = v.trim()
}

//修改
const confirm = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    loading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'collectNotice',
      api: 'save',
      override: {
        data: {
          ...formValue
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    message.success(res.msg)
    goBack()
  })
}
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}
.TShi {
  color: red;
  margin-left: 115px;
  margin-top: -20px;
  font-size: 13px;
}
.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
:deep(.w-e-text-container *, .w-e-toolbar *) {
  font-family: auto;
}
</style>
